import * as step from '@flow-step/step-toolkit'
import process from 'process'
import {getParams} from './params'
import {scan} from './scan'
import {setDependentFiles} from './utils'
import path from 'path'
import {installNode} from './install'
import * as fs from 'fs-extra'
import {setupJavaAndMaven} from './setupJava'

export const IS_LINUX = process.platform === 'linux'
export const IS_X64 = process.arch === 'x64'
const ENV_NAME_NODE_INSTALL_PATH: string = 'INSTALL_NODE_PATH'
export async function runStep(): Promise<void> {
    if (!IS_LINUX || !IS_X64) {
        throw new Error('JavaScriptCodeScan only supports Linux/amd64 systems now')
    }
    const params = getParams()

    step.info(`PIPELINE_ID=${params.pipelineID}`)
    step.info(`PIPELINE_NAME=${params.pipelineName}`)
    step.info(`BUILD_NUMBER=${params.buildNumber}`)
    step.info(`WORK_SPACE=${params.workSpace}`)
    step.info(`PROJECT_DIR=${params.projectDir}`)
    step.info(`PLUGIN_DIR=${params.pluginDir}`)
    step.info(`BUILD_JOB_ID=${params.buildJobID}`)
    step.info(`STEP_IDENTIFIER=${params.stepIdentifier}`)
    step.info(`USE_LOCAL_DEPENDENCIES=${params.localDependencies}`)
    step.info(`USE_LOCAL_RULES=${params.useLocalRules}`)
    step.info(`qualityGate=${params.redline}`)

    const installPath: string | undefined = process.env[ENV_NAME_NODE_INSTALL_PATH]
    await installNode(params.nodeVersion,'cnpm', installPath)
    await setupJavaAndMaven()

    const DependencyDir = path.join(params.pluginDir,'js-codescan')
    fs.mkdirSync(DependencyDir,{ recursive: true })
    await setDependentFiles(DependencyDir)
    await scan(params,DependencyDir);
}

runStep()
    .then(function() {
        step.success('run step successfully!')
    })
    .catch(function(err: Error) {
        step.error(err.message)
        process.exit(-1)
    })
